import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../core/utils/show_toast.dart';
import '../../../../data/controllers/exercises_controller.dart';
import '../../../gyms/gyms_page/models/gym.dart';
import '../models/exercise.dart';

part 'exercises_state.dart';

class ExercisesCubit extends Cubit<ExercisesState> {
  ExercisesCubit() : super(ExercisesInitial());

  static ExercisesCubit get(context) => BlocProvider.of(context);

  Gym? gym ;
  List <Exercise> exercises = [];

  void init({Gym? gym}) {
    if(gym!= null) {
      this.gym = gym;
    }
    getAllExercises();
  }

  Future getAllExercises()async{
    exercises = [];
    emit(ExercisesLoading());
    await ExercisesController.getAllExercises(gymId: gym?.gymId).catchError((e){
      emit(ExercisesError());
      return null;
    }).then((value){
      if(value != null && value.state) {
        exercises = List<Exercise>.generate(value.data.length, (index) => Exercise.fromJson(value.data[index]));
        emit(ExercisesDone());
      }else if(value != null){
        showMessage(value.message);
        emit(ExercisesError());
      }else{
        if (kDebugMode) {
          print('value is null');
        }
      }
    });
  }



}
